package com.clj.fastble.data;

import android.text.format.DateUtils;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleDataCountCallback.BleActivityCountCallback;
import com.clj.fastble.callback.BleDataCountCallback.BleAlarmClockCallback;
import com.clj.fastble.callback.BleDataCountCallback.BleBloodPressureCallback;
import com.clj.fastble.callback.BleDataCountCallback.BleDateCallback;
import com.clj.fastble.callback.BleDataCountCallback.BleFirmwareVersionCallback;
import com.clj.fastble.callback.BleDataCountCallback.BleHeartRateCallback;
import com.clj.fastble.callback.BleDataCountCallback.BleLostReminderCallback;
import com.clj.fastble.callback.BleDataCountCallback.BleStepCallback;
import com.clj.fastble.callback.BleDataCountCallback.BleUserInfoCallback;
import com.clj.fastble.callback.BleDataCountCallback.CharacteristicChangedCallback;
import com.clj.fastble.callback.BleNoticiCallback;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * @desc
 * @auth ${user}
 * @time 2019/2/28  17:2
 */
public class BleDataComponent implements CharacteristicChangedCallback {
    private static BleDataComponent comonent = new BleDataComponent();

    //    public static boolean canSyncStep = true;  //是否可以同步的标志
    private int stepCount, stepNum;
    private String sn;//活动序列号

    private BleDateCallback mBleDateCallback;
    private BleActivityCountCallback mBleActivityCountCallback;
    private BleStepCallback mBleStepCallback;
    private BleAlarmClockCallback mBleAlarmClockCallback;
    private BleNoticiCallback mBleNoticiCallback;
    private BleHeartRateCallback mBleHeartRateCallback;
    private BleBloodPressureCallback mBleBloodPressureCallback;
    private BleLostReminderCallback mBleLostReminderCallback;
    private BleFirmwareVersionCallback mBleFirmwareVersionCallback;
    private BleUserInfoCallback mBleUserInfoCallback;

    private BleDataComponent() {
    }


    public static BleDataComponent getDataComonent() {
        return comonent;
    }

    //设置时间
    public void setDate(BleDateCallback callback) {
        mBleDateCallback = callback;
        BleManager.getInstance().write(HexUtil.hexStringToBytes(formatDate()), null);
    }

    public String formatDate() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        BleLog.d("当前时间-----------" + "年" + String.valueOf(year) + "月" + String.valueOf(month) + "日" + String.valueOf(day)
                + "时" + String.valueOf(hour) + "分" + String.valueOf(minute) + "秒" + String.valueOf(second));
        StringBuilder builder = new StringBuilder("01");
        builder.append(HexUtil.formatTime(year / 100)).append(HexUtil.formatTime(year % 100)).append(HexUtil.formatTime(month + 1))
                .append(HexUtil.formatTime(day)).append(HexUtil.formatTime(hour)).append(HexUtil.formatTime(minute)).append(HexUtil.formatTime(second))
                .append("0713");
        return builder.toString();
    }


    public void getStep(String sn, int count, BleStepCallback stepCallback) {
        mBleStepCallback = stepCallback;
        this.sn = sn;
        String startTime = "00";
        switch (count) {
            case 0:
                startTime = "00";
                break;
            case 1:
                startTime = "06";
                break;
            case 2:
                startTime = "0c";
                break;
            case 3:
                startTime = "12";
            default:
                break;
        }
        BleManager.getInstance().write(HexUtil.hexStringToBytes("13" + sn + startTime), null);
    }

    public void getActivityCount(BleActivityCountCallback countCallback) {
      /*  if(!canSyncStep){
            return;
        }else{
            canSyncStep=false;
        }*/
        mBleActivityCountCallback = countCallback;
        setDate(new BleDateCallback() {
            @Override
            public void syncDate(boolean isSuccess) {
                if (isSuccess) {
                    BleManager.getInstance().write(HexUtil.hexStringToBytes("10"), null);
                }
            }
        });


    }

    /**
     * //1代表每天，2代表周一至周五，3代表周六周日
     *
     * @param list
     * @param bleAlarmClockCallback
     * @throws Exception
     */

    public void setAlarmClock(List<BleAlarmClockBean> list, BleAlarmClockCallback bleAlarmClockCallback) throws Exception {
        if (list.size() < 3) {
            throw new Exception("设置闹钟组数小于3组");
        }
        StringBuilder builder = new StringBuilder("03");
        this.mBleAlarmClockCallback = bleAlarmClockCallback;
        for (int i = 0; i < list.size(); i++) {
            BleAlarmClockBean bean = list.get(i);
            builder.append(HexUtil.formatTime(bean.getHour())).append(HexUtil.formatTime(bean.getMinute()));
            if (bean.getIsOpen() == 0) {
                builder.append("00");
            } else {
                if (bean.getRepeat() == 1) {
                    builder.append("7f");
                } else if (bean.getRepeat() == 2) {
                    builder.append("3e");
                } else if (bean.getRepeat() == 3) {
                    builder.append("41");
                }
            }
        }

        BleManager.getInstance().write(HexUtil.hexStringToBytes(builder.toString()), null);
    }


    /**
     * ，id为0，包数为2，来源是1，内容为：0xaa,0xbb….
     * Type数值表达的意思：
     * QQ:  0
     * 微信：1
     * 来电：2
     * 短信：3
     *
     * @param id                当前包id
     * @param count             当前id一共有几个包
     * @param type              当前包的来源类型
     * @param bleNoticiCallback 回调
     * @param content           内容
     */
    public void pushNotice(int id, int count, int type, byte[] content, BleNoticiCallback bleNoticiCallback) {
        mBleNoticiCallback = bleNoticiCallback;
        StringBuilder builder = new StringBuilder("20");
        builder.append(HexUtil.formatTime(id)).append(HexUtil.formatTime(count)).append(HexUtil.formatTime(type)).append(HexUtil.formatHexString(content));
        String string = builder.toString();
        BleManager.getInstance().write(HexUtil.hexStringToBytes(string), null);
    }


    public void pairBle() {
        BleLog.i("开始配对---------");

        BleManager.getInstance().write(new byte[]{0x72}, null);
    }

    /**
     * 设置是否震动
     *
     * @param type 0表示来电提醒，1表示蓝牙震动，2-9表示1-8个闹钟
     */
    public void setShake(int type) {
        byte[] bytes = new byte[20];
        bytes[0] = (byte) 0x2d;
        bytes[1] = (byte) 0x01;
        bytes[2] = (byte) type;
//        bytes[3]= (byte) 0xff;
        for (int i = 3; i < 9; i++) {
            bytes[i] = 0x01;
        }
        BleManager.getInstance().write(bytes, null);
    }


    /**
     * 发送完成同步指令
     */
    public void sendSyncFinished() {
        BleManager.getInstance().write(new byte[]{0x71}, null);
    }


    @Override
    public void change(byte[] data) {
        String s = HexUtil.formatHexString(data, true);
        BleLog.i("接收的特征值---------" + s);
        String[] split = s.split(" ");
        switch (split[0]) {
            case "81":
                if (null != mBleDateCallback) {
                    mBleDateCallback.syncDate(split[1].equals("00"));
                }
                break;
            case "90":
                if (null != mBleActivityCountCallback) {
                    /*int snNum = data[1];
                    if (data[2] == 7 && data[1] < 6) {
                        snNum = data[1] + 1;
                    }*/
                    mBleActivityCountCallback.getActivityCount(split[1]);
                }
                break;
            case "93":
                if (null != mBleStepCallback && !(split[1].equals("ff") && split[2].equals("ff"))) {
                    int step = 0;
                    for (int i = 6; i < split.length - 2; i += 2) {
                        if (!split[i].equals("ff")) {
                            step += (HexUtil.toHexInt(split[i]) * 256 + HexUtil.toHexInt(split[i + 1]));
                        }

                    }
                    stepNum += step;
                    stepCount++;
                    if (4 == stepCount) {
                        sendSyncFinished();
                        mBleStepCallback.getStep(stepNum);
//                        canSyncStep=true;
                        stepCount = 0;
                        stepNum = 0;
                    } else {
                        mBleStepCallback.getOneceStep(step);
                        getStep(sn, stepCount, mBleStepCallback);
                    }

                }
                break;
            case "83":
                if (null != mBleAlarmClockCallback) {
                    mBleAlarmClockCallback.setClockSuccess(split[1].equals("00"));
                }
                break;
            case "a0":
                if (null != mBleNoticiCallback) {
                    mBleNoticiCallback.noticiSuccess(split[2].equals("00"));
                }
                break;
            case "f2":
                BleLog.d("配对成功");
                break;
            case "ad":
                BleLog.d("震动写设置-----" + s);
                break;
            case "94":
                SimpleDateFormat format = new SimpleDateFormat("mm");
                String minute = format.format(new Date());
                break;
            case "c1":
                if (null != mBleLostReminderCallback) {
                    mBleLostReminderCallback.lostListner(split[1].equals("00"));
                }
                break;
            case "f0":
                String hexStr = s.replace(" ", "");
                String substring = hexStr.substring(2, hexStr.length() - 2);
                if (null != mBleFirmwareVersionCallback) {
                    BleLog.d("固件版本号----------" + HexUtil.decodeHexToASCII(substring));
                    mBleFirmwareVersionCallback.version(HexUtil.decodeHexToASCII(substring));
                }
                break;
            case "d6":
                if (null != mBleHeartRateCallback) {
                    BleLog.d("心率----------" + String.valueOf(HexUtil.toHexInt(split[2])));
                    mBleHeartRateCallback.heartRateData(String.valueOf(HexUtil.toHexInt(split[2])));
                }
                break;
            case "d7":
                if (null != mBleBloodPressureCallback) {
                    BleLog.d("血压----------" + String.valueOf(HexUtil.toHexInt(split[2])) + "-----" + String.valueOf(HexUtil.toHexInt(split[3])));
                    mBleBloodPressureCallback.bloodPressure(String.valueOf(HexUtil.toHexInt(split[2])), String.valueOf(HexUtil.toHexInt(split[3])));
                }
                break;
            case "f3":
                if (null != mBleUserInfoCallback) {
                    BleLog.d("身高---体重-------" + String.valueOf(HexUtil.toHexInt(split[1])) + "-----" + String.valueOf(HexUtil.toHexInt(split[2])));
                    mBleUserInfoCallback.info(HexUtil.toHexInt(split[1]), HexUtil.toHexInt(split[2]));
                }
                break;
            case "8b":
                if (split[1].equals("00")) {

                }
                break;
            case "8c":
                BleLog.d("写入身高---体重-------" + String.valueOf(HexUtil.toHexInt(split[1])));
                if (split[1].equals("00")) {
                    getUserInfo(new BleUserInfoCallback() {
                        @Override
                        public void info(int height, int weight) {
                            BleManager.WEIGHT = weight;
                            BleManager.HEIGHT = height;
                        }
                    });
                }
            default:
                break;
        }
    }


    //获取心率0x56,0x02
    public void getHeartRate(BleHeartRateCallback callback) {
        BleLog.i("获取心率----------------");
        this.mBleHeartRateCallback = callback;
        byte[] bytes = {0x56, 0x02};
        BleManager.getInstance().write(bytes, null);
    }

    /**
     * 0x57，0x01
     * 获取血压
     */
    public void getBooldPressure(BleBloodPressureCallback callback) {
        BleLog.i("获取血压----------------");
        this.mBleBloodPressureCallback = callback;
        byte[] bytes = {0x57, 0x01};
        BleManager.getInstance().write(bytes, null);
    }


    /**
     * 防丢提醒
     */
    public void lostReminder(BleLostReminderCallback lostReminderCallback) {
        this.mBleLostReminderCallback = lostReminderCallback;
        BleManager.getInstance().write(new byte[]{0x41, 0x00}, null);
    }


    /**
     * 获取固件版本号
     */
    public void getVersion(BleFirmwareVersionCallback versionCallback) {
        this.mBleFirmwareVersionCallback = versionCallback;
        BleManager.getInstance().write(new byte[]{0x70}, null);
    }

    /**
     * 进入空中升级
     */
    public void intoUpdate() {
        BleManager.getInstance().write(new byte[]{0x7F}, null);
    }

    /**
     * 获取个人信息
     */
    public void getUserInfo(BleUserInfoCallback userInfoCallback) {
        this.mBleUserInfoCallback = userInfoCallback;
        BleManager.getInstance().write(new byte[]{0x73}, null);
    }

    /*  (1)发送：0x0B, 0x00
      读取手环当前运动目标
      接收：0x8B, 0x00,RET,TARGET[0:1]
      TARGET  2字节的运动目标步数
       (2)发送：0x0B, 0x01, TARGET[0:1]
      设置手环当前运动目标
      接收：0x8B, 0x01,RET
      RET:返回值  0x00成功，  0x01….. 错误码*/
    public void readTargetStep(BleUserInfoCallback userInfoCallback) {
//      this.mBleUserInfoCallback=userInfoCallback;
        BleManager.getInstance().write(new byte[]{0x0B, 0x00}, null);
    }

    public void writeTargetStep(BleUserInfoCallback userInfoCallback) {
        this.mBleUserInfoCallback = userInfoCallback;
        BleManager.getInstance().write(new byte[]{0x0B, 0x01}, null);
    }


    //写入身高体重：
    //0x0C, HH,WW,SS,AA
    public void writeUserInfo() {
        byte[] bytes = new byte[5];
        bytes[0] = 0x0c;
        bytes[1] = (byte) 0xaf;
        bytes[2] = 0x4b;
        bytes[3] = 0x00;
        bytes[4] = 0x1c;
        BleManager.getInstance().write(bytes, null);
    }
}
